package com.richly.dto.base;

import com.richly.enums.IotEnum;
import com.richly.annotation.IotTableName;
import com.richly.utils.DataConvertUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: l_y
 * @Date: 2022/6/15 11:27
 * @FileName: Recordable
 * @Description: iot基类
 */

public interface Recordable {
    /**
     * 数据载入方法
     *
     * @return Record
     */

    default Record toRecord() {
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        Record record = new Record();
        record.setTime(Long.parseLong(format.format(getRecordableTime() == null ? new Date() : getRecordableTime())));
        Class aClass = this.getClass();
        IotTableName name = this.getClass().getAnnotation(IotTableName.class);
        record.setDeviceId(IotEnum.ROOT.getPathPrefix() + IotEnum.SPACE.getPathPrefix() +
                IotEnum.TEST.getPathPrefix() + name.value() + IotEnum.SPACE.getPathPrefix() + name.value());
        Field[] declaredFields = aClass.getDeclaredFields();
        List<String> measurements = new ArrayList<>();
        List<String> records = new ArrayList<>();
        try {
            for (Field field : declaredFields) {
                measurements.add(field.getName());
                String methodNamePro = field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
                Method methodName = this.getClass().getMethod("get" + methodNamePro);
                records.add(DataConvertUtils.convertDataType(methodName.invoke(this)));
            }
            record.setMeasurements(measurements);
            record.setValues(records);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return record;
    }

    /**
     * 获取时间
     *
     * @return Date
     */
    default Date getRecordableTime() {
        return null;
    }
}
